const { Op } = require('sequelize');
const { blogModel } = require('../models/model/blog');
const { blogTypeModel } = require('../models/model/blogType');
const { dataToJSON, dataDeleteOrUpdateRes } = require('../utils/tools');

// 添加
exports.createService = async (data) => {
	let res = await blogModel.create(data);
	return dataToJSON(res, '');
};

// 删除
exports.removeService = async (id) => {
	const res = await blogModel.destroy({ where: { id } });
	return dataDeleteOrUpdateRes(res);
};

// 修改
exports.updateService = async (data, id) => {
	const result = await blogModel.update(data, { where: { id } });
	return dataDeleteOrUpdateRes(result);
};

// 查单个
exports.findByIdService = async (id) => {
	const result = await blogModel.findOne({
		include: [
			{
				model: blogTypeModel,
				as: 'category' // 存放查询出数据的 key
			}
		],
		where: { id }
	});
	// 浏览数自增
	if (result) {
		result.scanNumber++;
		result.save();

		if (result?.toc) {
			result.toc = JSON.parse(result.toc);
		}
	}
	return dataToJSON(result, '');
};

// 查分页
exports.findByPageService = async (query) => {
	const size = Number(query.size) || 1;
	const limit = Number(query.limit) || 10;
	const params = {
		limit,
		offset: (size - 1) * limit,
		where: {},
		include: [
			{
				model: blogTypeModel,
				as: 'category' // 存放查询出数据的 key
			}
		]
	};
	if (query.title) {
		params.where.title = {
			[Op.like]: `%${query.title}%`
		};
	}
	if (query.categoryId) {
		params.where.categoryId = query.categoryId;
	}
	const { count, rows } = await blogModel.findAndCountAll(params);
	return JSON.parse(
		JSON.stringify({
			total: count,
			rows
		})
	);
};

/**
 * 更改文章中评论的
 * @param {*} id 文章类型id
 * @param {*} isAdd 是否增加
 * @param {*} value 直接给定固定值
 */
exports.commentCountChange = async (id, isAdd = true, value = null) => {
	const data = await blogModel.findByPk(id);
	if (!data) return;
	if (value != null) {
		data.commentNumber = value;
	} else {
		if (isAdd) {
			data.commentNumber++;
		} else {
			if (data.commentNumber >= 1) {
				data.commentNumber--;
			}
		}
	}
	await data.save();
};
